"use strict";

const Package = require("@medlog-cli-dev/package");
const logger = require("@medlog-cli-dev/log");
const path = require("path");
const { exec: spawn } = require("@medlog-cli-dev/utils");

let pkg;
const CACHE_DIR = "dependencies/";

// 命令行回车后直接调用该方法
async function exec() {
  let targetPath = process.env.CLI_TARGET_PATH;
  const homePath = process.env.CLI_HOME_PATH;
  let storeDir = "";
  // console.log("targetPath", targetPath);
  // console.log("homePath", homePath);

  // const cmdObj = arguments[arguments.length - 1]
  // const cmdName = cmdObj.name()
  //可以动态从服务端获取，这样一来，我们的package就相当于动态的一个库了
  const packageName = "@medlog-cli-dev/init";
  const packageVersion = "latest";

  if (!targetPath) {
    targetPath = path.resolve(homePath, CACHE_DIR);
    storeDir = path.resolve(targetPath, "node_modules");
    pkg = new Package({
      targetPath,
      storeDir,
      packageName,
      packageVersion,
    });
    if (await pkg.exists()) {
      // 更新package
      await pkg.update();
    } else {
      // 安装package
      await pkg.install();
    }
  } else {
    pkg = new Package({
      targetPath,
      packageName,
      packageVersion,
    });
  }
  const rootFile = pkg.getRootFilePath();
  if (rootFile) {
    try {
      const args = Array.from(arguments);
      args[args.length - 1] = handleCmds(args);
      const code = `require('${rootFile}').call(null,${JSON.stringify(args)})`;
      //win32下：cp.spawn('cmd',['/c','node','e',code])
      const child = spawn("node", ["-e", code], {
        cwd: process.cwd(),
        stdio: "inherit",
      });
      child.on("error", (e) => {
        console.info(e.message);
        process.exit(1);
      });
      child.on("exit", (e) => {
        console.log("命令执行成功" + e);
        process.exit(e);
      });
      // require(rootFile).call(null, Array.from(arguments))
    } catch (error) {}
  }
}

function handleCmds(params) {
  const args = params;
  const cmd = args[args.length - 1];
  const o = Object.create(null);
  Object.keys(cmd).forEach((key) => {
    if (cmd.hasOwnProperty(key) && !key.startsWith("_") && key !== "parent") {
      o[key] = cmd[key];
    }
  });
  return o;
}
module.exports = exec;
